/**
 * 作为slide的content
 * props.params {
 *   loanBillOID: 借款单OID，
 *   formOID: 借款单formOID，
 *   authorityWithLine: bool 是否含有行的操作权限 在我的借款、待还款、申请单创建的借款单跳进来的设为true 其他默认为false
 *   applicationOID: 申请单创建借款单的申请单OID,
 *   pathname: url，
 *   approverOID： 审批人oid，
 *   status：状态 目前我只看到审批在用
 * }
 */
import React, { Component, PropTypes } from "react";
import { connect } from 'react-redux';
import SlideDocument from 'components/template/slide-document/slide-document'
import borrowService from "../borrow-and-return.service";
import expenseReportService from "containers/expense-report/expense-report.service";
import { messages } from "share/common";
import { message } from 'antd'
import baseService from "share/base.service";
import 'styles/financial-management/finance-audit/slide-expense-report-detail/slide-expense-report-detail.scss'
import expenseService from "containers/my-account/expense.service";
import SlideLoanLeft from "./left/slide-loan-left";
import SlideLoanRight from "./right/slide-loan-right";
import SlideFrame from "components/slide-frame";
import editLoan from "../template/edit-loan";
import SlideLoanBar from "./bar/slide-loan-bar";
import financeAuditService from "../../financial-management/new-finance-audit/finance-audit.service";

@connect(mapStateToProps)
class SlideLoanDetail extends Component{

  state = {
    loading: false,
    info: {},
    form: {},
    isAuditInApproveStatus: false,
    pendingAudit: false,
    operator: false,
    templateCodeList: [],
    creditScore: {},
    applicant: {},
    jobInfo: {},
    requestInfo: {},
    auditFlag: false
  };

  componentDidMount() {
    this.getInfo(true);
  }

  componentWillUnmount() {
    const { user, loginUser } = this.props;
    loginUser.userOID !== user.userOID && baseService.changeLoginInfo(loginUser.userOID);
  }

  getInfo = isFirst => {
    const { loanBillOID, formOID, authorityWithLine = false, applicationOID, pathname } = this.props.params;
    this.setState({ loading: true });
    Promise.all([
      borrowService.getDetailInfo(loanBillOID, { showNodeName: true }),
      borrowService.getCustomForm(formOID),
      expenseReportService.getAuditChain(loanBillOID, 3001)
    ]).then(res => {
      const { loginUser } = this.props;
      const { chainDTO, prendingAudit } = res[2].data, info = res[0].data;
      const temp = loginUser.userOID !== info.applicantOID ? baseService.changeLoginInfo.bind(baseService) : () => {
        return new Promise(resolve => {
          resolve()
        });
      };
      temp(info.applicantOID, true).then(() => {
        const { options: { auditBaseConfig = {}} } = this.props;
        this.resDataHandle(res[1].data.customFormFields);
        let operator = authorityWithLine && info.status === 1001 && info.type === 2006 &&
          ((applicationOID && info.directCreate) || (!applicationOID && !info.directCreate));
        pathname.indexOf('finance-audit') > -1 && this.getAuditFlag(info.loanBillOID);
        let isAuditInApproveStatus = chainDTO && chainDTO.nodeType === 1012 && chainDTO.currentFlag;
        let isWaitForAudit = this.checkNewAuth() && ((info.status === 1003 && prendingAudit) || isAuditInApproveStatus)
          && pathname.indexOf('finance-audit') > -1;
        let isAuditEditable = isWaitForAudit && auditBaseConfig.reviewEditSuitable && auditBaseConfig.reviewEditEnable;
        this.setState({
          info,
          form: res[1].data,
          isAuditEditable: isAuditEditable,
          isAuditInApproveStatus: isAuditInApproveStatus,
          pendingAudit: prendingAudit,
          operator
        }, () => this.secondInterface(isFirst));
      });
    }).catch(() => {
      message.error(messages('finance-1.key28')/*系统异常*/);
      this.setState({loading: false})
    })
  };

  getAuditFlag = entityOID => {
    financeAuditService.getAuditFlag({ entityOID, entityType: 3001 }).then(res => {
      this.setState({ auditFlag: res.data });
    })
  };

  secondInterface = () => {
    const { info } = this.state;
    const { pathname, applicationOID } = this.props.params;
    let waitForAudit = pathname.indexOf('prending_audit') > -1;
    Promise.all([
      baseService.getHonestInfo(info.applicantOID, info.jobId),
      baseService.getUserInfo(info.applicantOID),
      expenseReportService.getJobInfo(info.jobId),
      waitForAudit && this.getCertificatePreviewTab(),
      applicationOID && borrowService.getRequestDetail(applicationOID),
    ]).then(res => {
      let templateCodeList = [];
      if (waitForAudit) {
        templateCodeList = (res[3] && res[3].data) ? res[3].data.filter(i => !!i.isEnable).map(i => i.templateCode) : [];
      }
      this.setState({
        loading: false,
        creditScore: res[0].data,
        jobInfo: res[2].data || {},
        templateCodeList,
        applicant: res[1].data,
        requestInfo: res[4] ? res[4].data : {}
      });
    })
  };

  getCertificatePreviewTab = () => {
    const { info } = this.state;
    //查询是否启用核算平台，若未启用则不展示凭证预览
    return expenseService.getAccountFlag().then(res => {
      if(!!res.data) {
        return expenseService.getCertificatePreviewTab(info.setOfBooksId, 'CSH_PRE_REQ')
      }
    });
  };

  resDataHandle = fields => {
    fields.map(item => {
      if (item.messageKey === 'applicant') {
        item.isReadOnly = true;
      }
    });
    fields.sort((a, b) => a.sequence > b.sequence || -1);
  };

  isShowHangUp = () => {
    const { info } = this.state;
    const { approverOID } = this.props.params;
    let showHangUp = false;
    info.approvalChains && info.approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  getChildContext() {
    const { applicant, creditScore, jobInfo, info, form, pendingAudit, isAuditInApproveStatus,
      templateCodeList, operator, auditFlag, isAuditEditable } = this.state;
    const { approverOID, pathname, applicationOID, status } = this.props.params;
    const { close, entry } = this.props;
    return {
      applicant,
      creditScore,
      jobInfo,
      info,
      form,
      isWaitForAudit: this.checkNewAuth() && ((info.status === 1003 && pendingAudit) || isAuditInApproveStatus),
      isShowHangUp: this.isShowHangUp(),
      approverOID: approverOID,
      templateCodeList,
      operator,
      pathname,
      applicationOID,
      close,
      isAuditInApproveStatus,
      getInfo: () => this.getInfo(false),
      status,
      auditFlag,
      entityType: 3001,
      isAuditEditable: isAuditEditable,
      entry
    }
  }

  onClickEditFields = () => {
    const { form, info, requestInfo, isAuditEditable } = this.state;
    SlideFrame.open({
      title: messages('finance-1.key39')/*编辑借款单*/,
      content: editLoan,
      params: {
        info,
        formInfo: form,
        requestInfo,
        isAuditEditable: isAuditEditable
      },
      afterClose: value => value && this.getInfo()
    }, this);
  };

  render() {
    const { loading, isAuditEditable } = this.state;
    const { company, loginUser } = this.props;
    return (
      <SlideDocument
        loading={loading}
        className='slide-expense-report-detail'
        fieldsParams={{
          annotateDisabled: true,
          showEdit: isAuditEditable,
          onClickEdit: this.onClickEditFields,
          showBookDate: true,
          company: company,
          user: loginUser,
          refreshInfo: this.getInfo
        }}
        left={<SlideLoanLeft/>}
        right={<SlideLoanRight/>}
        bar={<SlideLoanBar/>}
      />
    )
  }

  static childContextTypes = {
    applicant: PropTypes.object,
    creditScore: PropTypes.object,
    jobInfo: PropTypes.object,
    form: PropTypes.object,
    info: PropTypes.object,
    isWaitForAudit: PropTypes.bool,
    isShowHangUp: PropTypes.bool,
    approverOID: PropTypes.string,
    templateCodeList: PropTypes.array,
    operator: PropTypes.bool,
    pathname: PropTypes.string,
    applicationOID: PropTypes.string,
    close: PropTypes.func,
    isAuditInApproveStatus: PropTypes.bool,
    getInfo: PropTypes.func,
    status: PropTypes.string,
    auditFlag: PropTypes.bool,
    entityType: PropTypes.number,
    isAuditEditable: PropTypes.bool,
    entry: PropTypes.string
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    loginUser: state.login.loginUser,
    options: state.login.options,
    company: state.login.company
  }
}

export default SlideLoanDetail
